package coba.mailing.mail;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import coba.mailing.body.Body8;
import coba.mailing.jdbc.ConnectionFactory;
import coba.mailing.model.Solicitud;
import coba.mailing.procedure.AddAllCC;
import coba.mailing.procedure.AddAllTo;
import coba.mailing.properties.MainProperties;
import coba.mailing.query.FindSolicitudWhereFechaMail7y8IsNullAndFechaItinerarioBetween;
import coba.mailing.query.UpdateSolicitudFechaMail7y8;

public class Mail8 {

	public static void sendAll() throws ClassNotFoundException, IOException, SQLException, EmailException {
		Connection con = ConnectionFactory.getConnection();

		Calendar today0Hour = GregorianCalendar.getInstance();

		today0Hour.set(Calendar.HOUR_OF_DAY, 0);
		today0Hour.set(Calendar.MINUTE, 0);
		today0Hour.set(Calendar.SECOND, 0);
		today0Hour.set(Calendar.MILLISECOND, 0);

		Calendar _20daysAhead = GregorianCalendar.getInstance();
		_20daysAhead.add(Calendar.DATE, 20);

		/*
		 * Solicitudes dentro de los proximos 20 dias que aun no han recibido el mail.
		 */
		List<Solicitud> listSolicitud = FindSolicitudWhereFechaMail7y8IsNullAndFechaItinerarioBetween.
				find(con, today0Hour.getTime(), _20daysAhead.getTime());

		for (Solicitud solicitud : listSolicitud) {
			// verificar si el formulario fue enviado
			if (solicitud.getContactoEmail() != null && !solicitud.getContactoEmail().trim().equals("")) {
				if (solicitud.getFechaConfirmacionItinerario() != null) {
					send(solicitud);
					UpdateSolicitudFechaMail7y8.update(con, solicitud.getSolicitudId(), new Date());
				}
			}
		}

		con.close();
	}

	public static void send(Solicitud solicitud) throws EmailException, IOException {
		MainProperties mainProperties = MainProperties.getInstance();

		HtmlEmail email = new HtmlEmail();

		email.setCharset("utf-8");
		email.setHostName(mainProperties.getProperty("smtpServer"));
		email.setSmtpPort(Integer.valueOf(mainProperties.getProperty("smtpPort")));

		email.setFrom(mainProperties.getProperty("fromMail"), mainProperties.getProperty("fromName"));

		AddAllTo.addAllTo(email, solicitud.getContactoEmail());
		AddAllCC.addAllCC(email, mainProperties.getProperty("mail8Ccs"));

		email.setSubject("ConociendoBA - Visita " +
				new SimpleDateFormat("dd/MM").format(solicitud.getFechaItinerario()) +
				" recordatorio!");

		String cid = email.embed(ClassLoader.getSystemClassLoader().getResource("coba-mail-footer.jpg"), "Conociendo footer");

		email.setHtmlMsg(Body8.get(cid, solicitud));

		email.send();
	}

}
